<?php

namespace Addons\Weixinshare\Controller;
use Home\Controller\AddonsController;

class WeixinshareController extends AddonsController{
    private $appId;
    private $appSecret;
    public function __construct($appId='', $appSecret='') {
        if(!empty($appId) && !empty($appSecret)){
            $this->appId = $appId;
            $this->appSecret = $appSecret;
        }else{
            //获取配置信息
            $WeixinConfig=F('WeixinConfig');
            if(!$WeixinConfig){
                $result=M('addons')->where(array('name'=>'Weixinshare','status'=>1))->getField('config');
                $WeixinConfig=json_decode($result,true);
                F('WeixinConfig',$WeixinConfig);
            }
            $this->appId=$WeixinConfig['appid'];
            $this->appSecret=$WeixinConfig['appsecret'];
        }
    }
    public function getSignPackage() {
        $jsapiTicket = $this->getJsApiTicket();
        $url = "http://".$_SERVER[HTTP_HOST].$_SERVER[REQUEST_URI];
        $timestamp = time();
        $nonceStr = $this->createNonceStr();

        // 这里参数的顺序要按照 key 值 ASCII 码升序排序
        $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";

        $signature = sha1($string);
        $signPackage = array(
            "appId"     => $this->appId,
            "nonceStr"  => $nonceStr,
            "timestamp" => $timestamp,
            "url"       => $url,
            "signature" => $signature,
            "rawString" => $string
        );
        return $signPackage;
    }

    private function createNonceStr($length = 16) {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }

    public function getJsApiTicket() {
        $ticket=S('jsapi_ticket');
        if(!$ticket){
            $accessToken = $this->getAccessToken();
            $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken";
            $res = json_decode($this->https_request($url));
            $ticket = $res->ticket;
            if($ticket){
                S('jsapi_ticket',$ticket,array('type'=>'file','expire'=>7000));
            }
        }
        return $ticket;
    }

    private function getAccessToken() {
        $access_token=S('access_token');
        if(!$access_token){
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$this->appId&secret=$this->appSecret";
            $res = json_decode($this->https_request($url));
            $access_token = $res->access_token;
            if($access_token){
                S('access_token',$access_token,array('type'=>'file','expire'=>7000));
            }
        }
        return $access_token;
    }


    //发送http请求
    protected function https_request($url,$type='get',$data = null){

        $curl=curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if ($type=='post'){
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        $error=curl_error($curl);
        curl_close($curl);
        return $output;
    }
}
